# This is a so-called "R chunk" where you can write R code.
date()
## [1] "Mon Dec 12 12:30:01 2022"
The first week was somewhat heavy for me as I was ill and also a rookie with R. Hopefully things will start running more smoothly when getting more familiar with the language and learning to code on my own. Reading “the R for Health Data Science” and checking the code in RStudio simultaneously did not work too well for me. I felt it broke down the though process, even when the same things are presented in both. I think for me only the reading version would have been enough at this point as it describes the code also. I still get the point of having the RStudio version on the side to see how errors and such look like.
I find the material useful in getting to know R. For example the plotting part is excellent when learning how to draw nice plots. It also saves a lot of time when there is a material to guide one through the basics rather than starting by googling somewhat randomly to find the basic options. (Tried to learn something else by the latter method, not really advisable)
When I was looking for a course to study R, my supervisor recommended this course. My first impression of this course is, that this will be really useful indeed.
date()
## [1] "Mon Dec 12 12:30:01 2022"
First, read the data into R and inspect it.
# access libraries that will be needed at exercise 2
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.2
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0 ✔ purrr 0.3.5
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1
## ✔ readr 2.1.3 ✔ forcats 0.5.2
## Warning: package 'tibble' was built under R version 4.2.2
## Warning: package 'tidyr' was built under R version 4.2.2
## Warning: package 'readr' was built under R version 4.2.2
## Warning: package 'purrr' was built under R version 4.2.2
## Warning: package 'dplyr' was built under R version 4.2.2
## Warning: package 'stringr' was built under R version 4.2.2
## Warning: package 'forcats' was built under R version 4.2.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(ggplot2)
library(GGally)
## Warning: package 'GGally' was built under R version 4.2.2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
# let's have a look at the data
students2014 <- read.csv(file = '\\\\ad.helsinki.fi/home/h/hkonstar/Desktop/IDOS/IODS-project/data/exp2data.csv')
str(students2014)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : chr "F" "M" "F" "M" ...
## $ age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : int 25 12 24 10 22 21 21 31 24 26 ...
head(students2014)
## gender age attitude deep stra surf points
## 1 F 53 3.7 3.583333 3.375 2.583333 25
## 2 M 55 3.1 2.916667 2.750 3.166667 12
## 3 F 49 2.5 3.500000 3.625 2.250000 24
## 4 M 53 3.5 3.500000 3.125 2.250000 10
## 5 M 49 3.7 3.666667 3.625 2.833333 22
## 6 F 38 3.8 4.750000 3.625 2.416667 21
# if you prefer you may use the following instead or in addition
# glimpse(students2014)
This dataset consists of 7 variables and 166 observations.
Variable discriptions:
gender = F for female, M for male
age = age in years
attitude = points as mean for attitudes toward statistics
deep = points as mean for items related with deep approach to studying
stra = points as mean for items related with strategic approach to studying
surf = points as mean for items related with surface approach to studying
points = exam points
Visualize the data so that gender is distinguished. Use ggpairs to create matrix of plots from the variables in the dataset.
# create a plot matrix with ggpairs()
p <- ggpairs(students2014, mapping = aes(col = gender, alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
# draw the plot
p
# show summaries for variables in students2014
summary(students2014)
## gender age attitude deep
## Length:166 Min. :17.00 Min. :1.400 Min. :1.583
## Class :character 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333
## Mode :character Median :22.00 Median :3.200 Median :3.667
## Mean :25.51 Mean :3.143 Mean :3.680
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083
## Max. :55.00 Max. :5.000 Max. :4.917
## stra surf points
## Min. :1.250 Min. :1.583 Min. : 7.00
## 1st Qu.:2.625 1st Qu.:2.417 1st Qu.:19.00
## Median :3.188 Median :2.833 Median :23.00
## Mean :3.121 Mean :2.787 Mean :22.72
## 3rd Qu.:3.625 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :5.000 Max. :4.333 Max. :33.00
Visual inspection of the data revealed the following:
There is about double the amount of females in the data in respect to males. Scatterplot for points with attitudes indicates a linear interaction. Also for deep and stra there seems to be linear interaction.
Gender distribution for variables age, deep, and points seem similar. For attitude male distribution is more towards higher scores as for females it reminds more of normal distribution. For stra the case is the opposite for attitude distribution: females are having higher score. For surf females have sharp peaking normal distribution where males are leaning towards lower scores.
Numerical summaries for variables:
Following listing will have 1st and 3rd quadrants and median values for stated variable.
age: 21.0 - 27.0, mean 25.5
attitude: 2.6 - 3.1, median 3.2
deep: 3.3 - 4.1, median 3.7
stra: 2.6 - 3.6, median 3.2
surf: 2.4 - 3.2, median 2.8
points: 19.0 - 27.8, median 23.0
These state the same information as the graph functions.
Surf correlate negatively with attitude, deep, and stra. This means that when surf increases the other one decreases. When gender is taken into account stra is not correlated for males nor females. Attitude and deep are correlated negatively with surf only for male gender.
Points correlate positively with attitude meaning that points and attitude increase together. When gender is taken into account correlation is significant both for males and females.
First, select three variables which correlate highest with the points to be used as explanatory variables. Those are: attitude, stra, and surf.
Create a plot matrix and then a regression model having multiple explanatory variables.
# create an plot matrix with ggpairs()
ggpairs(students2014, lower = list(combo = wrap("facethist", bins = 20)))
# create a regression model with multiple explanatory variables
multiple_variables <- lm(points ~ attitude + stra + surf, data = students2014)
# print out a summary of the model
summary(multiple_variables)
##
## Call:
## lm(formula = points ~ attitude + stra + surf, data = students2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.1550 -3.4346 0.5156 3.6401 10.8952
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.0171 3.6837 2.991 0.00322 **
## attitude 3.3952 0.5741 5.913 1.93e-08 ***
## stra 0.8531 0.5416 1.575 0.11716
## surf -0.5861 0.8014 -0.731 0.46563
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared: 0.2074, Adjusted R-squared: 0.1927
## F-statistic: 14.13 on 3 and 162 DF, p-value: 3.156e-08
Inspecting the results show that points correlate in statistically significant manner only with variable attitude. Let’s remove the variables stra and surf from the model and use simple regression for variable attitude. Will do simple regression for attitude.
# a scatter plot of points versus attitude
qplot(attitude, points, data = students2014) + geom_smooth(method = "lm")
## Warning: `qplot()` was deprecated in ggplot2 3.4.0.
## `geom_smooth()` using formula = 'y ~ x'
# fit a linear model
linear_attitude <- lm(points ~ attitude, data = students2014)
# print out a summary of the model
summary(linear_attitude)
##
## Call:
## lm(formula = points ~ attitude, data = students2014)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.6372 1.8303 6.358 1.95e-09 ***
## attitude 3.5255 0.5674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
Inspecting the results show that adjusted R-squared is 0.19 indicating that attitude can explain about 19 % of the change in points.
Now, to check the assumptions we’ll produce diagnostics plots: Residuals vs Fitted values, Normal QQ-plot and Residuals vs Leverage.
# draw diagnostic plots using the plot() function. Choose the plots 1, 2 and 5; Residuals vs Fitted values, Normal QQ-plot, and Residuals vs Leverage
plot(linear_attitude, which = c(1,2,5))
Residuals vs Fitted plot
The line stays close to 0 indicating that the model works nicely for points up to 24 and less well for the points in the higher end. Observations 35, 56, and 145 are suggested as potential outliers.
Normal Q-Q plot
This probability plot indicates there is a linear connection and that the model fits nicely. For the low and high end the model fit is not. Observations 35, 56, and 145 are marked as possible outliers.
Residuals vs Leverage plot
The line stays quite close to 0, which indicates there are no major outliers in the data. Observations 35, 56, and 71 are marked as potential outliers.
Linear model is expected to have a good fit on the data. These diagnostic plots support the choice of linear model.
Read the data from csv file to R and check it looks fine.
#access libraries to be needed
library(boot)
## Warning: package 'boot' was built under R version 4.2.2
library(readr)
library(tidyverse)
library(dplyr)
library(GGally)
library(ggplot2)
library(finalfit)
## Warning: package 'finalfit' was built under R version 4.2.2
# read the data into a data frame
alc <- read.csv(file = "\\\\ad.helsinki.fi/home/h/hkonstar/Desktop/IDOS/IODS-project/data/alc.csv")
# print variable names
names(alc)
## [1] "school" "sex" "age" "address" "famsize"
## [6] "Pstatus" "Medu" "Fedu" "Mjob" "Fjob"
## [11] "reason" "guardian" "traveltime" "studytime" "schoolsup"
## [16] "famsup" "activities" "nursery" "higher" "internet"
## [21] "romantic" "famrel" "freetime" "goout" "Dalc"
## [26] "Walc" "health" "failures" "paid" "absences"
## [31] "G1" "G2" "G3" "alc_use" "high_use"
There are 370 observations and 35 variables in the data. Data set consists of survey data from students who have completed two different surveys, math and por. Data includes information about alcohol consumption, school grades and other school related items like time spent studying, and gemographic variables like parental education.
I will study relationship between high/low alcohol consumption and other variables that are: absences, studytime, failures, and G3.
High_use will correlate positively with absences (meaning that high alcohol usage is related with more absences)
High_use will correlate negatively with famrel (meaning that high alcohol usage is related with worse family relationships)
High_use will correlate negatively with health (meaning that high alcohol usage is related to worse health status)
High_use will correlate negatively with final grade (G3) (meaning that high alcohol usage is related with worse final grades)
# initialize a plot of high_use and absences
gabs <- ggplot(alc, aes(x = high_use, y = absences))
# define the plot as a box plot and draw it
gabs + geom_boxplot(aes(col=sex)) + ggtitle("Student absences by alcohol consumption and sex")
summary(alc$absences)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.000 1.000 3.000 4.511 6.000 45.000
# initialize a plot of high_use and quality of family relationships
gfam <- ggplot(alc, aes(x = high_use, y = famrel))
# define the plot as a box plot and draw it
gfam + geom_boxplot(aes(col=sex)) + ggtitle("Family relationship quality by alcohol consumption and sex")
summary(alc$famrel)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 4.000 4.000 3.935 5.000 5.000
# initialize a plot of high_use and health
ghlth <- ggplot(alc, aes(x = high_use, y = health))
# define the plot as a box plot and draw it
ghlth + geom_boxplot(aes(col=sex)) + ggtitle("Health by alcohol consumption and sex")
summary(alc$health)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 3.000 4.000 3.562 5.000 5.000
# initialize a plot of high_use and final grade (G3)
gfg <- ggplot(alc, aes(x = high_use, y = G3))
# define the plot as a box plot and draw it
gfg + geom_boxplot(aes(col=sex)) + ylab("final grade") + ggtitle("Final grade by alcohol consumption and sex")
summary(alc$G3)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.00 10.00 12.00 11.52 14.00 18.00
# tabulate data
dependent <- "high_use"
explanatory <- c("absences", "famrel", "health", "G3")
alc %>%
summary_factorlist(dependent, explanatory, p = TRUE,
add_dependent_label = TRUE)
## Dependent: high_use FALSE TRUE p
## absences Mean (SD) 3.7 (4.5) 6.4 (7.1) <0.001
## famrel Mean (SD) 4.0 (0.9) 3.8 (0.9) 0.019
## health Mean (SD) 3.5 (1.4) 3.7 (1.4) 0.134
## G3 Mean (SD) 11.8 (3.4) 10.9 (3.0) 0.011
Absences seem to increase slightly according to box plot. According to tabulation there is a connection. This supports my hypothesis.
According to both box plot and tabulation, high alcohol usage is connected with poorer family relationships. This is in line with my hypothesis.
For health, for box plot and tabulation show there is no difference. This did not support my hypothesis that health would decrease with high alcohol usage.
Final grade seems to decrease a bit with high alcohol use according to both, box plot and tabulation. This is aligned with my hypothesis.
I will start with a model including all four variables (even though it will be unneccary due to tabulation results). After that I will delete variables one by one, checking for AIC in between to see which model to choose and where to stop.
# find the model with glm()
m <- glm(high_use ~ absences + famrel + health + G3, data = alc, family = "binomial")
# print out a summary of the model
summary(m)
##
## Call:
## glm(formula = high_use ~ absences + famrel + health + G3, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.3498 -0.8206 -0.6820 1.1424 1.9666
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.12490 0.72091 0.173 0.862450
## absences 0.08193 0.02269 3.612 0.000304 ***
## famrel -0.27919 0.12753 -2.189 0.028582 *
## health 0.13687 0.08806 1.554 0.120138
## G3 -0.06840 0.03615 -1.892 0.058439 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 452.04 on 369 degrees of freedom
## Residual deviance: 423.36 on 365 degrees of freedom
## AIC: 433.36
##
## Number of Fisher Scoring iterations: 4
# print out the coefficients of the model
coef(m)
## (Intercept) absences famrel health G3
## 0.12490199 0.08193324 -0.27918935 0.13686832 -0.06840295
# compute odds ratios (OR)
OR <- coef(m) %>% exp()
# compute confidence intervals (CI)
CI <- confint(m)
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 1.1330374 -1.29609093 1.539770832
## absences 1.0853833 0.03949360 0.128701401
## famrel 0.7563967 -0.53111331 -0.029290043
## health 1.1466771 -0.03356517 0.312503540
## G3 0.9338841 -0.13975665 0.002411183
Let’s remove health from the explaining variables.
# find the model with glm()
m2 <- glm(high_use ~ absences + famrel + G3, data = alc, family = "binomial")
# print out a summary of the model
summary(m2)
##
## Call:
## glm(formula = high_use ~ absences + famrel + G3, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.2678 -0.8248 -0.6893 1.1897 2.0384
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.59749 0.65204 0.916 0.359486
## absences 0.08132 0.02276 3.574 0.000352 ***
## famrel -0.25491 0.12550 -2.031 0.042234 *
## G3 -0.07451 0.03574 -2.085 0.037091 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 452.04 on 369 degrees of freedom
## Residual deviance: 425.82 on 366 degrees of freedom
## AIC: 433.82
##
## Number of Fisher Scoring iterations: 4
# print out the coefficients of the model
coef(m2)
## (Intercept) absences famrel G3
## 0.59749109 0.08131699 -0.25491306 -0.07451065
# compute odds ratios (OR)
OR2 <- coef(m2) %>% exp()
# compute confidence intervals (CI)
CI2 <- confint(m2)
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR2, CI2)
## OR2 2.5 % 97.5 %
## (Intercept) 1.8175530 -0.68389274 1.882796853
## absences 1.0847147 0.03882378 0.128213991
## famrel 0.7749839 -0.50246478 -0.008594584
## G3 0.9281976 -0.14512892 -0.004553643
AIC is slightly worse with this model, but as the explaining variables all become significant and it is better to have fewer explanatory variables, I will continue with this model.
Explanatory model confidence intervals do not cross 0, which also indicates they are statistically significant. Just to be sure this model is the best fit, I will test a model without famrel.
# find the model with glm()
m3 <- glm(high_use ~ absences + G3, data = alc, family = "binomial")
# print out a summary of the model
summary(m3)
##
## Call:
## glm(formula = high_use ~ absences + G3, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.3286 -0.8298 -0.7219 1.2113 1.9242
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.38732 0.43500 -0.890 0.373259
## absences 0.08423 0.02309 3.648 0.000264 ***
## G3 -0.07606 0.03553 -2.141 0.032311 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 452.04 on 369 degrees of freedom
## Residual deviance: 429.93 on 367 degrees of freedom
## AIC: 435.93
##
## Number of Fisher Scoring iterations: 4
# print out the coefficients of the model
coef(m3)
## (Intercept) absences G3
## -0.38731815 0.08422737 -0.07605893
# compute odds ratios (OR)
OR3 <- coef(m3) %>% exp()
# compute confidence intervals (CI)
CI3 <- confint(m3)
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR3, CI3)
## OR3 2.5 % 97.5 %
## (Intercept) 0.6788751 -1.25260555 0.459482521
## absences 1.0878762 0.04110528 0.131708308
## G3 0.9267616 -0.14621889 -0.006471056
AIC is higher for this than for the second model. We will continue with the model having absences + famrel + G3 as explanatory variables.
# tabulate data
dependent <- "high_use"
explanatory2 <- c("absences", "famrel", "G3")
alc %>%
summary_factorlist(dependent, explanatory2, p = TRUE,
add_dependent_label = TRUE)
## Dependent: high_use FALSE TRUE p
## absences Mean (SD) 3.7 (4.5) 6.4 (7.1) <0.001
## famrel Mean (SD) 4.0 (0.9) 3.8 (0.9) 0.019
## G3 Mean (SD) 11.8 (3.4) 10.9 (3.0) 0.011
In this model, increase in school absences will add the likely hood for high alcohol use. Increase in famrel, that is better family relationships, and in G3 (final grade) will decrease the likely hood for high alcohol use.
These results do support my hypothesis that school absences would be positively related to high alcohol use. In line with hypothesis famrel and G3 were negatively related with high alcohol use. Experienced health was not related to alcohol usage, as I expected.
Use the model 2 having absences, famrel, and G3 as predictors.
# predict() the probability of high_use
probabilities <- predict(m2, type = "response")
# add the predicted probabilities to 'alc'
alc <- mutate(alc, probability = probabilities)
# use the probabilities to make a prediction of high_use
alc <- mutate(alc, prediction = high_use)
# see the last ten original classes, predicted probabilities, and class predictions
select(alc, failures, absences, sex, high_use, probability, prediction) %>% tail(10)
## failures absences sex high_use probability prediction
## 361 0 3 M FALSE 0.2410652 FALSE
## 362 1 0 M FALSE 0.3959997 FALSE
## 363 1 7 M TRUE 0.4361317 TRUE
## 364 0 1 F FALSE 0.1839390 FALSE
## 365 0 6 F FALSE 0.3704366 FALSE
## 366 1 2 F FALSE 0.2917307 FALSE
## 367 0 2 F FALSE 0.2398221 FALSE
## 368 0 3 F FALSE 0.5716255 FALSE
## 369 0 4 M TRUE 0.3645417 TRUE
## 370 0 2 M TRUE 0.2680314 TRUE
# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE TRUE
## FALSE 259 0
## TRUE 0 111
# initialize a plot of 'high_use' versus 'probability' in 'alc'
g <- ggplot(alc, aes(x = alc$probability, y = alc$high_use))
# define the geom as points and draw the plot
g + geom_point(aes(col = alc$prediction))
## Warning: Use of `alc$prediction` is discouraged.
## ℹ Use `prediction` instead.
## Warning: Use of `alc$probability` is discouraged.
## ℹ Use `probability` instead.
## Warning: Use of `alc$high_use` is discouraged.
## ℹ Use `high_use` instead.
# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.7 0.0 0.7
## TRUE 0.0 0.3 0.3
## Sum 0.7 0.3 1.0
# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)
}
# call loss_func to compute the average number of wrong predictions in the (training) data
loss_func(class = alc$probability, prob = 0)
## [1] 0.07567568
It is visible in the plot that low alcohol use is more likely than high alcohol usage. Cross tabulations of predictions vs actual values show that 70 % of the observations are low alcohol usage and the rest 30 % high alcohol usage. Predictions and actual values have equal proportions.
I will be using the Boston data set from late 1970s, which is about Housing values in suburbs of Boston. First the data set needs to uploaded, it is included in the MASS library.
# access the MASS package
library(MASS)
## Warning: package 'MASS' was built under R version 4.2.2
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
# load the data
data("Boston")
# explore the dataset
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506 14
Data consists of 506 observations and 14 variables. Variables are mostly numerical with 2 integer variables.
Variables include such as crime rate, proportion of owner-occupied old buildings, location related to river, percentage of the lower status population etc.
#access needed libraries
library(ggplot2)
library(dplyr)
library(tidyr)
library(tidyverse)
library(GGally)
# create plot matrixes with ggpairs()
p <- ggpairs(Boston[,1:5], lower = list(combo = wrap("facethist", bins = 20)))
p2 <- ggpairs(Boston[,6:10], lower = list(combo = wrap("facethist", bins = 20)))
# draw the plots
p
p2
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
Variable distributions differ greatly. In these plots showing half of the relationships, it seems that most of the variables are correlated with each other.
First, I will standardize the data set and view its summaries.
# center and standardize variables
boston_scaled <- scale(Boston)
# summaries of the scaled variables
summary(boston_scaled)
## crim zn indus chas
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-0.2723
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.2723
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.2723
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.:-0.2723
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 3.6648
## nox rm age dis
## Min. :-1.4644 Min. :-3.8764 Min. :-2.3331 Min. :-1.2658
## 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049
## Median :-0.1441 Median :-0.1084 Median : 0.3171 Median :-0.2790
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617
## Max. : 2.7296 Max. : 3.5515 Max. : 1.1164 Max. : 3.9566
## rad tax ptratio black
## Min. :-0.9819 Min. :-1.3127 Min. :-2.7047 Min. :-3.9033
## 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049
## Median :-0.5225 Median :-0.4642 Median : 0.2746 Median : 0.3808
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332
## Max. : 1.6596 Max. : 1.7964 Max. : 1.6372 Max. : 0.4406
## lstat medv
## Min. :-1.5296 Min. :-1.9063
## 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 3.5453 Max. : 2.9865
After scaling mean for each variable is 0, in addition variances for different variables became more uniform.
Now, categorical crime variable will be created and categorical break points are created based on quantiles from crim variable stating per capita crime rate by town. Data set is divided to train and test sets, so that 80% of randomly selected observations belong to train set.
# class of the boston_scaled object
class(boston_scaled)
## [1] "matrix" "array"
# this is matrix array, so needs to be changes to to data frame for further analysis
boston_scaled <- as.data.frame(boston_scaled)
# create a quantile vector of crime and print it
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
# create a categorical variable 'crime' by using the bins just created as break points
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label = c("low", "med_low", "med_high", "high"))
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# Creating random selection of the data, so that 80 % will belong to training set, and the rest 20 % to test set
# number of rows in the Boston data set
n <- nrow(boston_scaled)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- boston_scaled[ind,]
# create test set
test <- boston_scaled[-ind,]
We’ll do linear discriminant analysis to test how closely all other variables are located to crime variable in this data set. The data set was divided into two sets, a train set to teach the model and to test set to test how the model works. First, we will create the model and plot the results.
# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2400990 0.2673267 0.2475248 0.2450495
##
## Group means:
## zn indus chas nox rm age
## low 0.99180001 -0.8701087 -0.06938576 -0.8478298 0.45348074 -0.9071307
## med_low -0.09558931 -0.2999685 -0.05360128 -0.5831634 -0.12505512 -0.3798224
## med_high -0.41692168 0.2609809 0.12138096 0.3816519 0.06839516 0.4235020
## high -0.48724019 1.0171737 -0.03371693 1.0145834 -0.36163213 0.7884076
## dis rad tax ptratio black lstat
## low 0.8706946 -0.6835066 -0.7243046 -0.44755660 0.37384460 -0.79621870
## med_low 0.3561088 -0.5565130 -0.4836067 -0.05088499 0.31503887 -0.15518083
## med_high -0.3497061 -0.4202708 -0.2749374 -0.14297524 0.08582376 0.05065588
## high -0.8390026 1.6375616 1.5136504 0.78011702 -0.75224884 0.81550949
## medv
## low 0.537616321
## med_low 0.009923531
## med_high 0.078632760
## high -0.637934474
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.104667547 0.81438653 -0.94462155
## indus 0.031539052 -0.25881029 0.14553249
## chas -0.084593750 -0.03076103 0.11699956
## nox 0.396049067 -0.64436598 -1.45442450
## rm -0.089578106 -0.09663059 -0.21379545
## age 0.227173638 -0.37494188 -0.18154283
## dis -0.054866668 -0.42778473 0.10769834
## rad 3.169413444 1.05858970 0.07500531
## tax -0.006387405 -0.20627703 0.53333487
## ptratio 0.134618619 -0.03055214 -0.33034639
## black -0.129764754 0.02329682 0.11039470
## lstat 0.201959384 -0.24082943 0.44517693
## medv 0.180687919 -0.37511762 -0.17340838
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9461 0.0392 0.0147
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 2)
Observations categorized as high seem to cluster together far apart from other variables, even though there are some med_high observations as part of that cluster. Low, med_low, and med_high clusters are partly overlapping, yet they can still be distinguished from each other. Accessibility to radial high ways (variable rad) seems to have the highest impact on crime category “high”.
Further, train model will be used to predict categories in test data.
# save the crime categories from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 16 14 0 0
## med_low 2 10 6 0
## med_high 1 8 16 1
## high 0 0 0 28
Predictions were most accurate for high category, where everything (23) went to the right category. For med_high about half of the predictions were correct (17), and most mis-categorized were in med_low. For med_low about 2/3 of the predictions were correct (14) and most mis-categorized predictions were in med_high. For low less than half of the predictions were correctly located to low category (12) and almost all other predictions were categorized as med_low. It seems that quite often low and med_high categories are predicted as med_low.
All other variables together are not super good at predicting the crime variable. This is constant with the lda result from train data. Those above mentioned categories are overlapping and hence their prediction is difficult.
# reload the data
data("Boston")
# standardize data
boston_rescaled <- scale(Boston)
Distances between observations are calculated by two different methods: euclidean distance matrix and manhattan distance matrix.
# euclidean distance matrix
dist_eu <- dist(boston_rescaled)
# look at the summary of the distances
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(boston_rescaled, method = "manhattan")
# look at the summary of the distances
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
km <- kmeans(boston_rescaled, centers = 3)
# plot the Boston dataset with clusters
pairs(boston_rescaled[,1:5], col = km$cluster)
pairs(boston_rescaled[,6:10], col = km$cluster)
Here, I will investigate what is the optimal number of clusters.
set.seed(123)
# determine the number of clusters
k_max <- 8
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_rescaled, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')
Investigation shows that 2 is the optimal number for clusters, as there is an edgy turn on the graph. Let’s use that and visualize the clusters.
# k-means clustering
km2 <- kmeans(boston_rescaled, centers = 2)
# plot the Boston dataset with clusters
pairs(boston_rescaled[,1:5], col = km2$cluster)
pairs(boston_rescaled[,6:10], col = km2$cluster)
For some of the variables cluster colors do seems to fit the clusters nicely. For others, clusters are intermixed with each other and hence not so good at separating observations. When this version is compared with the three cluster version, this seems more tidy.
Here, I will plot the train data in 3D. I will plot the data twice, first by using crime categories as coloring and the using k-means clusters for coloring using the same number of clusters to see the effect of coloring strategy on the plot.
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
# Access the plotly package. Create a 3D plot of the columns of the matrix product using the crime classes in train data.
library(plotly)
## Warning: package 'plotly' was built under R version 4.2.2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = classes)
# Draw similar plot, but use k-means for setting colors.
# remove the crime variable from train data to run k-means
# use centers = 4 to compare the effect of k-means vs quantile in setting colors
trainkm <- dplyr::select(train, -crime)
kmtrain <- kmeans(trainkm, centers = 4)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = kmtrain$cluster)
Observations are located similarly in both plots. There is some difference in the coloring of the clusters. Here, I used same number of clusters for both to compare the effect of different clustering method. To summarize, observations are the same in both plots, yet coloring of them is different as quantile is set by the probability of those observations in belonging to particular fraction. K-mean on the other hand tries to minimize the mean distance between geometric points, that is, it is more sensitive for the composition of the data.
# load libraries to be used
library(tidyverse)
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.2.2
## corrplot 0.92 loaded
library(GGally)
library(ggplot2)
# read the data into a data frame
human <- read.csv(file = "\\\\ad.helsinki.fi/home/h/hkonstar/Desktop/IDOS/IODS-project/data/human.csv", row.names = 1) %>% as.data.frame()
#visualize data and show summary
ggpairs(human)
summary(human)
## Edu2.FM Labo.FM Life.Exp Edu.Exp
## Min. :0.1717 Min. :0.1857 Min. :49.00 Min. : 5.40
## 1st Qu.:0.7264 1st Qu.:0.5984 1st Qu.:66.30 1st Qu.:11.25
## Median :0.9375 Median :0.7535 Median :74.20 Median :13.50
## Mean :0.8529 Mean :0.7074 Mean :71.65 Mean :13.18
## 3rd Qu.:0.9968 3rd Qu.:0.8535 3rd Qu.:77.25 3rd Qu.:15.20
## Max. :1.4967 Max. :1.0380 Max. :83.50 Max. :20.20
## GNI Mat.Mor Ado.Birth Parli.F
## Min. : 581 Min. : 1.0 Min. : 0.60 Min. : 0.00
## 1st Qu.: 4198 1st Qu.: 11.5 1st Qu.: 12.65 1st Qu.:12.40
## Median : 12040 Median : 49.0 Median : 33.60 Median :19.30
## Mean : 17628 Mean : 149.1 Mean : 47.16 Mean :20.91
## 3rd Qu.: 24512 3rd Qu.: 190.0 3rd Qu.: 71.95 3rd Qu.:27.95
## Max. :123124 Max. :1100.0 Max. :204.80 Max. :57.50
str(human)
## 'data.frame': 155 obs. of 8 variables:
## $ Edu2.FM : num 1.007 0.997 0.983 0.989 0.969 ...
## $ Labo.FM : num 0.891 0.819 0.825 0.884 0.829 ...
## $ Life.Exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Edu.Exp : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ GNI : int 64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
## $ Mat.Mor : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Ado.Birth: num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Parli.F : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
cor(human) %>% corrplot(, type = "upper")
There are 8 variables and 155 observations in the data set. Variable distributions vary a lot. Some follow normal distribution, others do not. Life.Exp and Edu.Exp as well as Mat.Mor and Ado.Birth have the highest positive correlation. Life.Exp and Mat.Mor on the hand have highest negative correlation. Just mentioned two “clusters” (Life.Exp + Edu.Exp and Mat.Mor + Ado.Birth) correlate negatively with each other.
# perform principal component analysis (with the SVD method)
pca_human <- prcomp(human)
# Show the variability captured by the principal components.
summary(pca_human)
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## Standard deviation 1.854e+04 185.5219 25.19 11.45 3.766 1.566 0.1912 0.1591
## Proportion of Variance 9.999e-01 0.0001 0.00 0.00 0.000 0.000 0.0000 0.0000
## Cumulative Proportion 9.999e-01 1.0000 1.00 1.00 1.000 1.000 1.0000 1.0000
# draw a biplot of the principal component representation and the original variables
biplot(pca_human, choices = 1:2, cex = c(0.8, 1), col = c("grey40", "deeppink2"))
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
Data was not standardized, so let’s standardize it and redo what was just done.
# standardize data
human_std <- scale(human)
# perform principal component analysis (with the SVD method)
pca_human_std <- prcomp(human_std)
# Show the variability captured by the principal components.
summary(pca_human_std)
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## Standard deviation 2.0708 1.1397 0.87505 0.77886 0.66196 0.53631 0.45900
## Proportion of Variance 0.5361 0.1624 0.09571 0.07583 0.05477 0.03595 0.02634
## Cumulative Proportion 0.5361 0.6984 0.79413 0.86996 0.92473 0.96069 0.98702
## PC8
## Standard deviation 0.32224
## Proportion of Variance 0.01298
## Cumulative Proportion 1.00000
# draw a biplot of the principal component representation and the original variables
biplot(pca_human_std, choices = 1:2, cex = c(0.8, 1), col = c("grey40", "deeppink2"))
Standardization makes it possible to compare variables with each other. Standardized results resemble visualized data, whereas non-standardized results were quite different. For instance, non-standardized biplot shows GNI as the most impactfull variable, where as for the standardized data results resemble correlations for original data. Standardized results give more defined results.
Life expectancy, female/male proportion having secondary education, expected year of education, and Gross national income appear together and they have an opposite effect than maternal mortality and number of children being born. These relate to PC1 that explains the most of the variance in the data that is about 54% in this case. Female/male proportion on participating in labour and women representation in parliament have similar effect. These explain about 16% of the variance in the data, and they are mostly related to PC2.
# load tea data set
tea <- read.csv("https://raw.githubusercontent.com/KimmoVehkalahti/Helsinki-Open-Data-Science/master/datasets/tea.csv", stringsAsFactors = TRUE) %>% as.data.frame()
#explore the data
str(tea)
## 'data.frame': 300 obs. of 36 variables:
## $ breakfast : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
## $ tea.time : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
## $ evening : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
## $ lunch : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ dinner : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
## $ always : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
## $ home : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
## $ work : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
## $ tearoom : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
## $ friends : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
## $ resto : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
## $ pub : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ sugar : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ where : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ price : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
## $ age : int 39 45 47 23 48 21 37 36 40 37 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
## $ SPC : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
## $ Sport : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
## $ age_Q : Factor w/ 5 levels "+60","15-24",..: 4 5 5 2 5 2 4 4 4 4 ...
## $ frequency : Factor w/ 4 levels "+2/day","1 to 2/week",..: 3 3 1 3 1 3 4 2 1 1 ...
## $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
## $ spirituality : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
## $ healthy : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
## $ diuretic : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
## $ friendliness : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
## $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
## $ feminine : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
## $ sophisticated : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
## $ slimming : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ exciting : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
## $ relaxing : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
## $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
dim(tea)
## [1] 300 36
view(tea)
#rselect subsets to be drawn
tea1 <- tea[,1:9] %>% as.data.frame()
tea2 <- tea[,10:18] %>% as.data.frame()
tea3 <- tea[,20:29] %>% as.data.frame()
tea4 <- tea[,30:36] %>% as.data.frame()
#visualize data
pivot_longer(tea1, cols = everything()) %>%
ggplot(aes(value)) + facet_wrap("name", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
pivot_longer(tea2, cols = everything()) %>%
ggplot(aes(value)) + facet_wrap("name", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
pivot_longer(tea3, cols = everything()) %>%
ggplot(aes(value)) + facet_wrap("name", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
pivot_longer(tea4, cols = everything()) %>%
ggplot(aes(value)) + facet_wrap("name", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
Data consists of 300 observations and 36 variables. Questionnaire data about how people drink their tea (18 items), how they perceive the product (12 items), and personal details (4 items).
I chose variables Tea, How, sugar, age_Q, and sex.
library(FactoMineR)
## Warning: package 'FactoMineR' was built under R version 4.2.2
library(tidyr)
# column names to keep in the dataset
keep_columns <- c("Tea", "How", "sugar", "age_Q", "sex")
# select the 'keep_columns' to create a new dataset
tea_time <- select(tea, keep_columns)
## Warning: Using an external vector in selections was deprecated in tidyselect 1.1.0.
## ℹ Please use `all_of()` or `any_of()` instead.
## # Was:
## data %>% select(keep_columns)
##
## # Now:
## data %>% select(all_of(keep_columns))
##
## See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
# multiple correspondence analysis
mca <- MCA(tea_time, graph = FALSE)
# summary of the model
summary(mca)
##
## Call:
## MCA(X = tea_time, graph = FALSE)
##
##
## Eigenvalues
## Dim.1 Dim.2 Dim.3 Dim.4 Dim.5 Dim.6 Dim.7
## Variance 0.325 0.279 0.248 0.228 0.205 0.188 0.182
## % of var. 14.777 12.672 11.277 10.365 9.335 8.528 8.292
## Cumulative % of var. 14.777 27.449 38.726 49.091 58.426 66.954 75.246
## Dim.8 Dim.9 Dim.10 Dim.11
## Variance 0.165 0.149 0.120 0.111
## % of var. 7.491 6.765 5.461 5.037
## Cumulative % of var. 82.738 89.503 94.963 100.000
##
## Individuals (the 10 first)
## Dim.1 ctr cos2 Dim.2 ctr cos2 Dim.3 ctr cos2
## 1 | 0.270 0.075 0.029 | 0.535 0.342 0.113 | 0.244 0.080 0.024
## 2 | 0.983 0.990 0.391 | -0.191 0.043 0.015 | -0.248 0.082 0.025
## 3 | 0.309 0.098 0.072 | -0.733 0.643 0.405 | -0.444 0.264 0.148
## 4 | -0.745 0.570 0.472 | 0.004 0.000 0.000 | 0.176 0.042 0.026
## 5 | 0.214 0.047 0.031 | -0.170 0.035 0.020 | -0.606 0.493 0.248
## 6 | -0.307 0.097 0.082 | -0.273 0.089 0.065 | -0.077 0.008 0.005
## 7 | 0.143 0.021 0.010 | 0.004 0.000 0.000 | -0.109 0.016 0.006
## 8 | 0.912 0.852 0.278 | -0.016 0.000 0.000 | 0.249 0.083 0.021
## 9 | 0.252 0.065 0.024 | 0.292 0.102 0.032 | -0.014 0.000 0.000
## 10 | 0.708 0.514 0.201 | 0.258 0.080 0.027 | -0.009 0.000 0.000
##
## 1 |
## 2 |
## 3 |
## 4 |
## 5 |
## 6 |
## 7 |
## 8 |
## 9 |
## 10 |
##
## Categories (the 10 first)
## Dim.1 ctr cos2 v.test Dim.2 ctr cos2 v.test
## black | 1.117 18.927 0.408 11.050 | 0.429 3.255 0.060 4.244 |
## Earl Grey | -0.494 9.648 0.440 -11.466 | -0.242 2.705 0.106 -5.622 |
## green | 0.383 0.994 0.018 2.330 | 0.454 1.628 0.025 2.761 |
## alone | -0.100 0.399 0.019 -2.353 | -0.303 4.292 0.171 -7.149 |
## lemon | -0.397 1.064 0.019 -2.411 | 0.757 4.521 0.071 4.601 |
## milk | 0.209 0.564 0.012 1.864 | 0.458 3.158 0.056 4.082 |
## other | 2.155 8.569 0.144 6.552 | 0.593 0.757 0.011 1.804 |
## No.sugar | 0.604 11.599 0.390 10.800 | -0.353 4.628 0.133 -6.317 |
## sugar | -0.646 12.399 0.390 -10.800 | 0.378 4.947 0.133 6.317 |
## +60 | 1.095 9.337 0.174 7.208 | 0.751 5.130 0.082 4.948 |
## Dim.3 ctr cos2 v.test
## black 0.374 2.782 0.046 3.701 |
## Earl Grey 0.124 0.795 0.028 2.875 |
## green -1.563 21.658 0.302 -9.500 |
## alone -0.262 3.589 0.127 -6.167 |
## lemon 0.842 6.280 0.088 5.116 |
## milk -0.023 0.009 0.000 -0.209 |
## other 2.749 18.270 0.234 8.358 |
## No.sugar -0.305 3.867 0.099 -5.448 |
## sugar 0.326 4.134 0.099 5.448 |
## +60 0.907 8.407 0.119 5.975 |
##
## Categorical variables (eta2)
## Dim.1 Dim.2 Dim.3
## Tea | 0.481 0.106 0.313 |
## How | 0.172 0.177 0.349 |
## sugar | 0.390 0.133 0.099 |
## age_Q | 0.565 0.445 0.440 |
## sex | 0.018 0.533 0.039 |
# visualize MCA
plot(mca, invisible=c("ind"), graph.type = "classic", habillage = "quali")
People using milk or other things with their tea, favoring green or black tea and being 35-44 or +60 year old have positive effect on both dimension 1 and 2. Choose Earl Grey, not adding anything to tea, and being 15-24 years-old have negative effect on dimensions 1 and 2.
For dim1 gender does not have an effect, but for dim2 there seems to be an opposite effect for gender.
Among these selected variables there does not seem to be any clusters that could clearly explain the variability in the data.
First load the data sets and make sure they are ready to be used.
library(tidyverse)
# Read the BPRS and RATS data
BPRSL <- read.table("\\\\ad.helsinki.fi/home/h/hkonstar/Desktop/IDOS/IODS-project/data/BPRSL.csv", sep =",", header = T)
RATSL <- read.table("\\\\ad.helsinki.fi/home/h/hkonstar/Desktop/IDOS/IODS-project/data/RATSL.csv", sep =",", header = T)
# Look at the (column) names of BPRS
names(BPRSL)
## [1] "treatment" "subject" "weeks" "bprs" "week"
# Look at the structure of BPRS
str(BPRSL)
## 'data.frame': 360 obs. of 5 variables:
## $ treatment: int 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : int 1 2 3 4 5 6 7 8 9 10 ...
## $ weeks : chr "week0" "week0" "week0" "week0" ...
## $ bprs : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week : int 0 0 0 0 0 0 0 0 0 0 ...
# Print out summaries of the variables
summary(BPRSL)
## treatment subject weeks bprs week
## Min. :1.0 Min. : 1.00 Length:360 Min. :18.00 Min. :0
## 1st Qu.:1.0 1st Qu.: 5.75 Class :character 1st Qu.:27.00 1st Qu.:2
## Median :1.5 Median :10.50 Mode :character Median :35.00 Median :4
## Mean :1.5 Mean :10.50 Mean :37.66 Mean :4
## 3rd Qu.:2.0 3rd Qu.:15.25 3rd Qu.:43.00 3rd Qu.:6
## Max. :2.0 Max. :20.00 Max. :95.00 Max. :8
#do same for RATS
names(RATSL)
## [1] "ID" "Group" "WD" "Weight" "Time"
str(RATSL)
## 'data.frame': 176 obs. of 5 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : int 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr "WD1" "WD1" "WD1" "WD1" ...
## $ Weight: int 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int 1 1 1 1 1 1 1 1 1 1 ...
summary(RATSL)
## ID Group WD Weight
## Min. : 1.00 Min. :1.00 Length:176 Min. :225.0
## 1st Qu.: 4.75 1st Qu.:1.00 Class :character 1st Qu.:267.0
## Median : 8.50 Median :1.50 Mode :character Median :344.5
## Mean : 8.50 Mean :1.75 Mean :384.5
## 3rd Qu.:12.25 3rd Qu.:2.25 3rd Qu.:511.2
## Max. :16.00 Max. :3.00 Max. :628.0
## Time
## Min. : 1.00
## 1st Qu.:15.00
## Median :36.00
## Mean :33.55
## 3rd Qu.:50.00
## Max. :64.00
Need to factorize some of the variables and also change the data.frame to tibble.
# need to refactor some variables
BPRSL$treatment <- factor(BPRSL$treatment)
BPRSL$subject <- factor(BPRSL$subject)
RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
#change to tibble
library(tibble)
BPRSL <- as.tibble(BPRSL)
## Warning: `as.tibble()` was deprecated in tibble 2.0.0.
## ℹ Please use `as_tibble()` instead.
## ℹ The signature and semantics have changed, see `?as_tibble`.
RATSL <- as.tibble(RATSL)
#check structure
str(BPRSL)
## tibble [360 × 5] (S3: tbl_df/tbl/data.frame)
## $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ weeks : chr [1:360] "week0" "week0" "week0" "week0" ...
## $ bprs : int [1:360] 42 58 54 55 72 48 71 30 41 57 ...
## $ week : int [1:360] 0 0 0 0 0 0 0 0 0 0 ...
str(RATSL)
## tibble [176 × 5] (S3: tbl_df/tbl/data.frame)
## $ ID : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr [1:176] "WD1" "WD1" "WD1" "WD1" ...
## $ Weight: int [1:176] 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int [1:176] 1 1 1 1 1 1 1 1 1 1 ...
Now data seems as it was at the end of data wrangling and we are ready to analyze.
Let’s plot the data for visual inspection.
#Access the package ggplot2
library(ggplot2)
# Draw the plot
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
theme(legend.position = "none") +
scale_y_continuous(limits = c(min(RATSL$Weight), max(RATSL$Weight)))
Data has not been standardized, so let’s do that and then replot. Note, there is one outlier in Group 2, but let’s keep that for now.
# Standardise the variable Weight
RATSL <- RATSL %>%
group_by(Time) %>%
mutate(stdweight = scale(Weight)) %>%
ungroup()
# Plot again with the standardised weight
library(ggplot2)
ggplot(RATSL, aes(x = Time, y = stdweight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
scale_y_continuous(name = "standardized weight")
Results look relatively same as they did before standardizing, yet the scale is different. Let’s draw a summary graph.
# Number of subjects (per group):
n <- 16
library(dplyr)
library(tidyr)
# Summary data with mean and standard error of Weight by Group and Time
RATSS <- RATSL %>%
group_by(Group, Time) %>%
summarise(mean = mean(Weight), se = sd(Weight)) %>%
ungroup()
## `summarise()` has grouped output by 'Group'. You can override using the
## `.groups` argument.
# Plot the mean profiles
library(ggplot2)
ggplot(RATSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
geom_line() +
scale_linetype_manual(values = c(1,2,3)) +
geom_point(size=3) +
scale_shape_manual(values = c(1,2,3)) +
geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) +
theme(legend.position = c(0.8,0.8)) +
scale_y_continuous(name = "mean(Weight) +/- se(Weight)")
As expected by the outlier in Group 2, standard error is quite big indicating a lot variability within the values of the group. Let’s still keep that in and draw boxplots for the mean weights for the treatments.
library(dplyr)
library(tidyr)
# Create a summary data by treatment and subject with mean as the summary variable (ignoring baseline Time 1, indicating firt day of weighting)
RATSL8S <- RATSL %>%
filter(Time > 1) %>%
group_by(Group, ID) %>%
summarise( mean=mean(Weight) ) %>%
ungroup()
## `summarise()` has grouped output by 'Group'. You can override using the
## `.groups` argument.
# Glimpse the data
glimpse(RATSL8S)
## Rows: 16
## Columns: 3
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
## $ mean <dbl> 263.2, 238.9, 261.7, 267.2, 270.9, 276.2, 274.6, 267.5, 443.9, 4…
# Draw a boxplot of the mean versus treatment
library(ggplot2)
ggplot(RATSL8S, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), days 8-64")
Now, let’s exclude the outlier in group 2.
# Create a new data by filtering the outlier and adjust the ggplot code the draw the plot again with the new data
RATSL8S1 <- filter(RATSL8S, RATSL8S$mean < 580)
ggplot(RATSL8S1, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), days 8-64")
Mean weight for group two has now about the same variance as the other groups. Value for Group 2 mean is about 50 grams lighter without the outlier.
T-test and anova
There are three groups and t-test can only have two. T-tests are done in three sets. Correction for multiple test should be done, but not executed here.
# Perform a two-sample t-test
with(RATSL8S1, t.test(mean[Group == 1], mean[Group == 2]))
##
## Welch Two Sample t-test
##
## data: mean[Group == 1] and mean[Group == 2]
## t = -31.481, df = 5.9935, p-value = 6.92e-08
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -201.9427 -172.8073
## sample estimates:
## mean of x mean of y
## 265.025 452.400
with(RATSL8S1, t.test(mean[Group == 1], mean[Group == 3]))
##
## Welch Two Sample t-test
##
## data: mean[Group == 1] and mean[Group == 3]
## t = -22.592, df = 3.8997, p-value = 2.792e-05
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -295.0616 -229.8884
## sample estimates:
## mean of x mean of y
## 265.025 527.500
with(RATSL8S1, t.test(mean[Group == 2], mean[Group == 3]))
##
## Welch Two Sample t-test
##
## data: mean[Group == 2] and mean[Group == 3]
## t = -6.436, df = 3.8644, p-value = 0.003373
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -107.95111 -42.24889
## sample estimates:
## mean of x mean of y
## 452.4 527.5
# all comparisons are statistically significant indicating differences in treatment groups
library(dplyr)
library(tidyr)
# Add the baseline from the original data as a new variable to the summary data
RATSL8S2 <- RATSL8S %>%
mutate(baseline = RATSL$Time[1])
# Fit the linear model with the mean as the response
fit <- lm(mean ~ baseline + Group, data = RATSL8S2)
# Compute the analysis of variance table for the fitted model with anova()
anova(fit)
## Analysis of Variance Table
##
## Response: mean
## Df Sum Sq Mean Sq F value Pr(>F)
## Group 2 238620 119310 88.525 2.679e-08 ***
## Residuals 13 17521 1348
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
t <- lm(mean ~ Group, data = RATSL8S1)
anova(t)
## Analysis of Variance Table
##
## Response: mean
## Df Sum Sq Mean Sq F value Pr(>F)
## Group 2 207659 103830 501.81 2.721e-12 ***
## Residuals 12 2483 207
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Results from t-tests and anova indicate that diet group had significant impact on body weight.
Let’s plot the data to visualize the effect of treatment on bprs score.
library(dplyr)
library(tidyr)
# Check the dimensions of the data
dim(BPRSL)
## [1] 360 5
# Plot the data
library(ggplot2)
ggplot(BPRSL, aes(x = week, y = bprs, group = treatment)) +
geom_smooth(aes(linetype = treatment)) + scale_x_continuous(name = "week") + scale_y_continuous(name = "bprs (points)") + theme(legend.position = "top")
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
Both treatments seem to decrease the bprs score, indicating severity of symptoms related with schizophrenia. This suggest both treatments alleviate schitzophrenic symptoms.
# create a regression model BPRS_reg
BPRS_reg <- lm(bprs ~ week + treatment, data = BPRSL)
# print out a summary of the model
summary(BPRS_reg)
##
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.454 -8.965 -3.196 7.002 50.244
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 46.4539 1.3670 33.982 <2e-16 ***
## week -2.2704 0.2524 -8.995 <2e-16 ***
## treatment2 0.5722 1.3034 0.439 0.661
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared: 0.1851, Adjusted R-squared: 0.1806
## F-statistic: 40.55 on 2 and 357 DF, p-value: < 2.2e-16
Random intercept model
# access library lme4
library(lme4)
## Warning: package 'lme4' was built under R version 4.2.2
## Loading required package: Matrix
## Warning: package 'Matrix' was built under R version 4.2.2
##
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
# Create a random intercept model
BPRS_ref <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
# Print the summary of the model
summary(BPRS_ref)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2748.7 2768.1 -1369.4 2738.7 355
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0481 -0.6749 -0.1361 0.4813 3.4855
##
## Random effects:
## Groups Name Variance Std.Dev.
## subject (Intercept) 47.41 6.885
## Residual 104.21 10.208
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 1.9090 24.334
## week -2.2704 0.2084 -10.896
## treatment2 0.5722 1.0761 0.532
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.437
## treatment2 -0.282 0.000
Random Intercept and Random Slope Model
# create a random intercept and random slope model
library(lme4)
BPRS_ref1 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
# print a summary of the model
summary(BPRS_ref1)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2745.4 2772.6 -1365.7 2731.4 353
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.8919 -0.6194 -0.0691 0.5531 3.7976
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.8222 8.0512
## week 0.9609 0.9802 -0.51
## Residual 97.4305 9.8707
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 2.1052 22.066
## week -2.2704 0.2977 -7.626
## treatment2 0.5722 1.0405 0.550
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.582
## treatment2 -0.247 0.000
# perform an ANOVA test on the two models
anova(BPRS_ref1, BPRS_ref)
## Data: BPRSL
## Models:
## BPRS_ref: bprs ~ week + treatment + (1 | subject)
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref 5 2748.7 2768.1 -1369.4 2738.7
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4 7.2721 2 0.02636 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Random Intercept and Random Slope Model with interaction
# create a random intercept and random slope model with the interaction
library(lme4)
BPRS_ref2 <- lmer(bprs ~ week + treatment + (week | subject) + week*treatment, data = BPRSL, REML = FALSE)
# print a summary of the model
summary(BPRS_ref2)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject) + week * treatment
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2744.3 2775.4 -1364.1 2728.3 352
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0512 -0.6271 -0.0768 0.5288 3.9260
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.9964 8.0620
## week 0.9687 0.9842 -0.51
## Residual 96.4707 9.8220
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 47.8856 2.2521 21.262
## week -2.6283 0.3589 -7.323
## treatment2 -2.2911 1.9090 -1.200
## week:treatment2 0.7158 0.4010 1.785
##
## Correlation of Fixed Effects:
## (Intr) week trtmn2
## week -0.650
## treatment2 -0.424 0.469
## wek:trtmnt2 0.356 -0.559 -0.840
# perform an ANOVA test on the two models
anova(BPRS_ref2, BPRS_ref1)
## Data: BPRSL
## Models:
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## BPRS_ref2: bprs ~ week + treatment + (week | subject) + week * treatment
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4
## BPRS_ref2 8 2744.3 2775.4 -1364.1 2728.3 3.1712 1 0.07495 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# draw the plot with the bprs values
ggplot(BPRSL, aes(x = week, y = bprs, group = treatment)) +
geom_smooth(aes(linetype = treatment)) +
scale_x_continuous(name = "week") +
scale_y_continuous(name = "bprs score") +
theme(legend.position = "top")
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
# Create a vector of the fitted values
Fitted <- fitted(BPRS_ref2)
library(dplyr)
library(tidyr)
# Create a new column fitted
BPRSL <- BPRSL %>% mutate(Fitted)
# draw the plot with the Fitted values
library(ggplot2)
ggplot(BPRSL, aes(x = week, y = Fitted, group = treatment)) +
geom_smooth(aes(linetype = treatment)) +
scale_x_continuous(name = "week") +
scale_y_continuous(name = "bprs score") +
theme(legend.position = "top")
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'